<?php

/**
 * This is the model class for table "observations".
 *
 * The followings are the available columns in table 'observations':
 * @property string $observation_ID
 * @property string $observation_date
 * @property double $observation_longitude
 * @property double $observation_latitude
 * @property integer $seeing
 * @property integer $transparency
 * @property string $groupnorth
 * @property string $spotnorth
 * @property string $groupsouth
 * @property string $spotsouth
 * @property string $grouptotal
 * @property string $spottotal
 * @property string $wolff
 * @property double $correction
 * @property string $user_ID
 * @property string $telescope_ID
 * @property string $image
 *
 * The followings are the available model relations:
 * @property Images[] $images
 * @property Telescopes $telescope
 * @property Users $user
 */
class Observation extends CActiveRecord
{ 
    public $from_date;
    public $to_date;
    public $image;
    
	/**
	 * Returns the static model of the specified AR class.
	 * @param string $className active record class name.
	 * @return Observation the static model class
	 */
	public static function model($className=__CLASS__)
	{
		return parent::model($className);
	}

	/**
	 * @return string the associated database table name
	 */
	public function tableName()
	{
		return 'observations';
	}

	/**
	 * @return array validation rules for model attributes.
	 */
	public function rules()
	{
		// NOTE: you should only define rules for those attributes that
		// will receive user inputs.
		return array(
			array('observation_date, observation_longitude, observation_latitude, 
                    seeing, transparency, groupsouth, spotsouth, groupnorth, 
                    spotnorth, telescope', 
                    'required'
                ),
            array('image', 'file', 'types'=>'jpg, gif, png', 'safe'=>true, 'allowEmpty'=>true),
			array('seeing, transparency', 'numerical', 'integerOnly'=>true),
			array('observation_longitude, observation_latitude, correction', 'numerical'),
			array('groupnorth, spotnorth, groupsouth, spotsouth, grouptotal, spottotal, wolff, user_ID, telescope_ID', 'length', 'max'=>10),
            array('observation_date', 'date', 'format'=>'dd-MM-yyyy'),
			// The following rule is used by search().
			// Please remove those attributes that should not be searched.
			array('observation_ID, observation_date, observation_longitude, observation_latitude, seeing, transparency, groupnorth, spotnorth, groupsouth, spotsouth, grouptotal, spottotal, wolff, correction, user_ID, telescope_ID', 'safe', 'on'=>'search'),
		);
	}

	/**
	 * @return array relational rules.
	 */
	public function relations()
	{
		// NOTE: you may need to adjust the relation name and the related
		// class name for the relations automatically generated below.
		return array(
			'images' => array(self::HAS_MANY, 'Images', 'observation_ID'),
			'telescope' => array(self::BELONGS_TO, 'Telescopes', 'telescope_ID'),
			'user' => array(self::BELONGS_TO, 'Users', 'user_ID'),
		);
	}

	/**
	 * @return array customized attribute labels (name=>label)
	 */
	public function attributeLabels()
	{
		return array(
			'observation_ID' => 'Observation',
			'observation_date' => 'Observatie Datum',
			'observation_longitude' => 'Observatie Longitude',
			'observation_latitude' => 'Observatie Latitude',
			'seeing' => 'Seeing',
			'transparency' => 'Transperantie',
			'groupnorth' => 'Groepnoord',
			'spotnorth' => 'Vleknoord',
			'groupsouth' => 'Groepzuid',
			'spotsouth' => 'Vlekzuid',
			'grouptotal' => 'Groeptotaal',
			'spottotal' => 'Vlektotaal',
			'wolff' => 'Wolffgetal',
			'correction' => 'Correctie',
			'user_ID' => 'Waarnemer',
			'telescope_ID' => 'Telescoop',
		);
	}
	/**
	 * Retrieves a list of models based on the current search/filter conditions.
	 * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
	 */
	public function search()
	{
		$criteria=new CDbCriteria;

		$criteria->compare('observation_ID',$this->observation_ID,true);
		$criteria->compare('observation_date',$this->observation_date,true);
		$criteria->compare('observation_longitude',$this->observation_longitude);
		$criteria->compare('observation_latitude',$this->observation_latitude);
		$criteria->compare('seeing',$this->seeing);
		$criteria->compare('transparency',$this->transparency);
		$criteria->compare('groupnorth',$this->groupnorth,true);
		$criteria->compare('spotnorth',$this->spotnorth,true);
		$criteria->compare('groupsouth',$this->groupsouth,true);
		$criteria->compare('spotsouth',$this->spotsouth,true);
		$criteria->compare('grouptotal',$this->grouptotal,true);
		$criteria->compare('spottotal',$this->spottotal,true);
		$criteria->compare('wolff',$this->wolff,true);
		$criteria->compare('correction',$this->correction);
		$criteria->compare('user_ID',$this->user_ID,true);
        
        /*
         * Set the range of the observation date to search.
         */
        if(!empty($this->from_date) && empty($this->to_date))
        {
            $criteria->condition = "observation_date >= :from_date";
            $criteria->params = array(':from_date'=>$this->formatDateString($this->from_date, 'dd-MM-yyyy', 'Y-m-d'));
        }else if(!empty($this->to_date) && empty($this->from_date))
        {
            $criteria->condition = "observation_date <= :to_date";
            $criteria->params = array(':to_date'=>$this->formatDateString($this->to_date, 'dd-MM-yyyy', 'Y-m-d'));
        }else if(!empty($this->to_date) && !empty($this->from_date))
        {
            $criteria->condition = "observation_date  >= :from_date AND observation_date <= :to_date";
            $criteria->params = array(
                    ':to_date'=>$this->formatDateString($this->to_date, 'dd-MM-yyyy', 'Y-m-d'), 
                    ':from_date'=>$this->formatDateString($this->from_date, 'dd-MM-yyyy', 'Y-m-d'),
                );
        }
        
        $criteria->order = 'observation_date DESC';

		return new CActiveDataProvider($this, array(
			'criteria'=>$criteria,
		));
	}
    
    /**
     * Helper function to convert date from one format to another.
     * 
     * @param string $dateString
     * @param string $fromFormat - Yii format
     * @param string $toFormat - DateTime format
     * @return string
     */
    public function formatDateString($dateString, $fromFormat, $toFormat){
        // Convert from string to different format
        return date($toFormat, CDateTimeParser::parse($dateString, $fromFormat));
    }
        
    public function getObservationDateInput()
    {
        // Convert from MySQL datetime format to local format
        return date('d-m-Y', CDateTimeParser::parse($this->observation_date, 'yyyy-MM-dd hh:mm:ss'));
    }

    public function setObservationDateInput($value)
    {
        // Convert from local format to MySQL datetime format
        $this->observation_date = Yii::app()->dateFormatter->formatDateTime(CDateTimeParser::parse($value, 'yyyy-MM-dd'),'medium',null);
    }
    
    /**
     * Executed just before save() is called.
     * 
     * @return type
     */
    protected function beforeSave() 
    {
        // Set correct date format for saving in MySQL
        $this->observation_date = Yii::app()->dateFormatter->format(
                'yyyy-MM-dd', 
                CDateTimeParser::parse(
                        $this->observation_date, 
                        'dd-MM-yyyy')
                );
        
        return parent::beforeSave();
    }


    /**
     * Create string for presenting images with observation.
     * 
     * @return string
     */
    public function getImage()
    {
        // Create array with image-data for this observation
        $_image_list = CHtml::listData(Image::model()->findAllByAttributes(
                    array(
                        'observation_ID'=>$this->observation_ID,
                    )
                ),'image_ID','image_name');
        
        // Start string
        $_images_string = '<ul>';
        foreach($_image_list as $_image_ID=>$_image_name) { 
            // Build image element with correct src.
            $_images_string .= '<li><img src="'.Yii::app()->params['UPLOAD_DIR_URL'].'/'.$this->user_ID.
                    '_'.$this->observation_ID.
                    '_'.$_image_ID.'_'.$_image_name.'" /></li>';                
           }
        $_images_string .= '</ul>';
        
        return $_images_string;
    }
    
    /**
     * Create string to present the user for this observation.
     * 
     * @return string
     */
    public function getUser()
    {
        $_user_string = '';
        
        $_observation_user = User::model()->findByPk($this->user_ID);
        
        if($_observation_user)        
        {
            $_user_string .= $_observation_user->firstname;
            $_user_string .= ($_observation_user->prefix?' '.$_observation_user->prefix:'');
            $_user_string .= ' '.$_observation_user->lastname;
            
        }
        
        return $_user_string;
    }
    
    /**
     * Create string to present telescope.
     * 
     * @return string
     */
    public function getTelescope()
    {
        $_telescope_string = '';
        
        $_observation_telescope = Telescope::model()->findByPk($this->telescope_ID);
        
        if($_observation_telescope)        
        {
            $_telescope_string .= $_observation_telescope->name;
            $_telescope_string .= ' ('.$_observation_telescope->magnification.'x)';
            
        }
        
        return $_telescope_string;
    }
    
    public function getObservationName()
    {
        return $this->getUser().' - '.$this->getObservationDateInput();
    }
}